package com.soft.springhrms.controller;

import com.soft.springhrms.pojo.Positions;
import com.soft.springhrms.service.EmployeesService;
import com.soft.springhrms.service.PositionsService;
import com.soft.springhrms.utils.RedisUtil;
import com.soft.springhrms.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/positions")
public class GetPositionController {
    @Autowired
    private PositionsService positionService;
    @Autowired
    private EmployeesService employeeService;
    @Autowired
    private RedisUtil redisUtil;
    @GetMapping
    public List<Positions> getAllPositions() {
        return positionService.getAllPositions();
    }
    @PostMapping
    public ResultVO addPosition(@RequestBody Positions position) {
        redisUtil.deleteWithDelay("positionsList");
        return ResultVO.success(positionService.save(position),"添加职位成功");
    }
    @DeleteMapping("/{id}")
    public ResultVO deletePosition(@PathVariable Integer id) {
        int employeeCount = employeeService.countByPosition(id);
        if (employeeCount > 0) {
            return ResultVO.error(400,"该职位下有员工，无法删除");
        }
        redisUtil.deleteWithDelay("positionsList");
        boolean result = positionService.removeById(id);
        return ResultVO.success(result,"删除成功");
    }
    @PutMapping("/{id}")
    public  ResultVO editPosition(@PathVariable Integer id,@RequestBody Positions position){
        try{ redisUtil.deleteWithDelay("positionsList");
        return ResultVO.success(positionService.updateById(position),"修改职位成功");}catch (Exception e){
            e.printStackTrace();
        }
        return ResultVO.error(404,"修改职位失败");
    }
}
